package com.ruoyi.ex.service;


import cn.hutool.core.collection.IterUtil;
import com.doudou.core.container.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.doudou.core.container.MapUtil;
import com.doudou.core.container.SetUtil;
import com.doudou.core.str.StrUtil;
import com.ruoyi.ex.domain.ExQuestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service("exService")
public class ExService {

    @Autowired private IExQuestionService exQuestionService;

    /**
     * 返回做对的题目数量
     * @param answers {
     *     13:[
     *         "B"
     *     ],
     *     14:"C",
     *     50:[
     *         "B",
     *         "C"
     *     ]
     * }
     * @return { 14:['C'] }
     */
    public Map<Long, Object> rightTotal(Map<Long, Object> answers,String questionIds){
        return rightTotal(answers,JSONUtil.toList(questionIds,Long.class));
    }
    public Map<Long, Object> rightTotal(Map<Long, Object> answers,List<Long> questionIds){
        Map<Long,Object> rightMap = MapUtil.linkedHashMap();
        for (Long questionId : questionIds) {
            String v = answers.get(questionId) + "";
            List<Character> answerArr = ListUtil.list(false);
            //查询题目
            ExQuestion question = exQuestionService.selectExQuestionById(questionId);
            if (ObjectUtil.isNotEmpty(v)){
                answerArr = JSONUtil.isTypeJSONArray(v) ?
                        JSONUtil.toList(v, Character.class) :   //多选题
                        JSONUtil.toList(StrUtil.BRACKET_START + v + StrUtil.BRACKET_END, Character.class);  //单选题
            }
            if (isEqualList(question.getAnswerList(), answerArr)){
                rightMap.put(questionId,v);
            }
        }
        return rightMap;
    }

    /**
     * 比较两个集合是否相等
     * @param coll1 对题集合
     * @param coll2 答题集合
     */
    private boolean isEqualList(List<Character> coll1,List<Character> coll2){
        if (IterUtil.isEmpty(coll2)) {
            return false;
        }
        if (coll1.size() != coll2.size()) {
            return false;
        }
        return SetUtil.equals(coll1,coll2);
    }
}
